package cn.gson.school.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import cn.gson.school.dao.ImagesDao;
import cn.gson.school.dao.xitong.UserDao;
import cn.gson.school.entity.xitong.ImageEntity;
import cn.gson.school.entity.xitong.UserEntity;
import cn.gson.school.service.ImagesService;

@Controller
@RequestMapping("/biz")
public class BizController {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private ImagesService imgService;

	@Autowired
	private ImagesDao imgDao;

	@Autowired
	private UserDao userDao;

	@GetMapping
	public void index(Model model) {
		model.addAttribute("atts", imgDao.findAll());
	}

	@GetMapping("update/touxiang")
	public String toUpdate() {
		return "biz/update";
	}

	@PostMapping("update/touxiang")
	public String update(@SessionAttribute("user") UserEntity user, @RequestParam("file") MultipartFile file,
			HttpSession session) throws Exception {
		ImageEntity imgs=imgDao.findOne(user.getImagesId());
		String oldTouxiang = imgs.getImagePath();
		// 保存头像
		ImageEntity img = imgService.upload(user, "touxiang", file,null);
		// 修改用户头像字段信息
		user.setImagesId(imgs.getImageId());
		userDao.save(user);
		// 删除原有头像文件信息
		imgService.drop(oldTouxiang);
		// 刷新session中的user信息
		session.setAttribute("user", user);
		// 成功后回到原来的页面
		return "redirect:/biz";
	}
	
	@PostMapping("create/user")
	public String createUser(
			@ModelAttribute("u") @Valid UserEntity user,
			@RequestParam("file") MultipartFile file,BindingResult br) throws Exception {
		if(!br.hasErrors()) {
			//选择了头像
			if(file != null && !file.isEmpty()) {
				//新建用户
				userDao.save(user);
				//保存头像
				ImageEntity img = imgService.upload(user, "avatar", file,null);
				//更新用户邮箱字段
				user.setImagesId(img.getImageId());
				//更新用户信息
				userDao.save(user);
				return "redirect:/biz";
			}
		}
		return "biz";
	}
}